package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //1. 判断老人是否已经入住
        // 通过身份证号查询老人
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));
        if (elder != null) {
            return;
        }
        //2.更新床位的状态为已入住
        //根据床位的id查询床位的实体对象
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        //更新床位的状态
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.保存或更新老人的数据
        elder = insertOrUpdateElder(dto, bed);
        //4.新增签约办理
        insertContract(elder, dto);
        //5.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);
        //6.新增入住配置信elderFamilyDtoList = {ArrayList@19622}  size = 1息
        insertCheckInConfig(checkIn, dto);
    }

    /**
     * 第四次抽取方法
     * 新增入住配置信息
     *
     * @param checkIn
     * @param dto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto dto) {
        //准备入住配置信息
        CheckInConfig checkInConfig = new CheckInConfig();
        //属性拷贝，补全数据
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        //存储数据到数据库
        checkInConfigMapper.insert(checkInConfig);
    }


    /**
     * 第三次抽取方法
     * 新增入住信息
     *
     * @param elder
     * @param dto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        //准备入住信息
        CheckIn checkIn = new CheckIn();
        //补全数据
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0L);
        //存储数据到数据库
        this.save(checkIn);
        return checkIn;
    }

    /**
     * 第二次抽取方法
     * 新增签约办理
     *
     * @param elder
     * @param dto
     */
    private void insertContract(Elder elder, CheckInApplyDto dto) {
        //准备合同
        Contract contract = new Contract();
        //属性拷贝，补全数据
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());//设置合同编号
        contract.setElderId(Integer.valueOf(elder.getId() + ""));
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        if (startDate.isBefore(LocalDateTime.now())) {
            contract.setStatus(1L);
        } else {
            contract.setStatus(0L);
        }
        //存储数据到数据库
        contractMapper.insert(contract);
    }

    /**
     * 第一次抽取方法
     * 保存或更新老人的数据
     */
    private Elder insertOrUpdateElder(CheckInApplyDto dto, Bed bed) {
        //准备老人的数据
        Elder newElder = new Elder();
        //属性拷贝，补全数据
        BeanUtils.copyProperties(dto.getCheckInElderDto(), newElder);
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());
        newElder.setStatus(1);
        // 查询老人信息，（身份证号、状态不为1）
        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .ne(Elder::getStatus, 1));//状态不为1
        //判断老人信息是否存在
        if (oldElder != null) {
            //存在则修改
            elderMapper.updateById(newElder);
        } else {
            //不存在则添加
            elderMapper.insert(newElder);
        }
        return newElder;
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //创建返回对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查旬入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //获取老人信息并拷贝
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        //获取年龄
        checkInElderVo.setAge(getAge(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //查询合同信息
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, checkIn.getElderId()));
        checkInDetailVo.setContract(contract);
        //查询入住配置信息并设置
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //查询入住家人信息
        // 从数据库获取JSON字符串
        String remarkJson = checkIn.getRemark();
        // 将JSON字符串转换回对象列表
        List<ElderFamilyVo> familyList = JSON.parseObject(remarkJson, new TypeReference<List<ElderFamilyVo>>() {
        });
        checkInDetailVo.setElderFamilyVoList(familyList);
        return checkInDetailVo;
    }

    /**
     * 根据身份证号获取年龄
     */
    private int getAge(String idCardNo) {
        int oldYear = Integer.parseInt(idCardNo.substring(6, 10));
        int newYear = LocalDate.now().getYear();
        int ageStr = (newYear - oldYear);
        return ageStr;
    }
}
